package cn.kgc.mybatis.dao.impl;

import cn.kgc.mybatis.dao.UserDao;
import cn.kgc.mybatis.entity.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;
import java.sql.SQLException;
import java.util.List;

/**
 * @author: mosin
 * @version: v1.0  2022/9/26
 */
public class UserDaoMyBatisImpl implements UserDao {

    @Override
    public List<User> selectAll() throws SQLException {

        // 1.SqlSessionFactoryBuilder
        SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
        try {
            InputStream resourceAsStream = Resources.getResourceAsStream("mybatis-config.xml");
            // SqlSessionFactory
            SqlSessionFactory factory = sqlSessionFactoryBuilder.build(resourceAsStream);
            //从 SqlSessionFactory 中获取 SqlSession
            SqlSession sqlSession = factory.openSession();
            // SqlSession 提供了在数据库执行 SQL 命令所需的所有方法
            List<User> users = sqlSession.selectList("user.selectAll");
            System.out.println("users = " + users);

            return users;

        } catch (IOException e) {
            e.printStackTrace();
        }


        return null;
    }

    @Override
    public Integer delete(Integer id) {

        // 1.SqlSessionFactoryBuilder
        SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
        try {
            InputStream resourceAsStream = Resources.getResourceAsStream("mybatis-config.xml");
            // SqlSessionFactory
            SqlSessionFactory factory = sqlSessionFactoryBuilder.build(resourceAsStream);
            //从 SqlSessionFactory 中获取 SqlSession   不会自动提交事务
            //SqlSession sqlSession = factory.openSession();

            // SqlSessionFactory 中获取 SqlSession   会自动提交事务
            SqlSession sqlSession = factory.openSession(true);
            // SqlSession 提供了在数据库执行 SQL 命令所需的所有方法  delete
            int delete = sqlSession.delete("user.delete", id);
            System.out.println("delete:"+delete);

            //手动提交事务  factory.openSession();
            //sqlSession.commit();

            return delete;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
